package com.cloud.controller;

import java.util.ArrayList;
import java.util.List;

public class ByteHandler {
    int lastReceivedByte = 0;
    List<String> buffer = new ArrayList<>();

    public void write(final int[] b, final int off, final int len){
        int offset = off;
        int blockStartOffset = offset;
        int remaining = len;

        int readIndex = off;
        int lastValue = b[off];

        while(readIndex < len){
            if(b[readIndex] != 1 && b[readIndex] != 2){
                if(buffer.size() > 0 && (lastValue==1 || lastValue==2)){
                    buffer.add("\\n");
                }
                buffer.add(String.valueOf(b[readIndex]));
            }
            lastValue = b[readIndex];
            readIndex++;
        }

//        while (remaining > 0){
//            while (remaining > 0 && b[offset] != 1 && b[offset] != 2 ){
//                offset ++;
//                remaining --;
//            }
//            int blockLength = offset - blockStartOffset;
//            if(blockLength > 0){
//                bufferWrite(b, blockStartOffset, blockLength);
//                lastReceivedByte = 0;
//            }
//            while(remaining > 0 && (b[offset] == 1 || b[offset] == 2)){
//                writen(b[offset]);
//                offset ++;
//                remaining --;
//            }
//            blockStartOffset = offset;
//        }
    }

    public void writen(final int c){
        if(c == 1 || c == 2){
            if(lastReceivedByte != 1 && lastReceivedByte != 2){
                buffer.add("\\n");
            }
        }else{
            buffer.add(String.valueOf(c));
        }
        lastReceivedByte = c;
    }

    public void bufferWrite(final int[] b, int start, int length){
        for(int i = start; i < start+length; i++ ){
            buffer.add(String.valueOf(b[i]));
        }
    }

    public List<String> getBuffer() {
        return buffer;
    }

    public static void main(String[] args) {
        final int[] b = {1,2,4,5,6,1,2,4,5,7,1,2,4,5,8};
        final int off = 0;
        final int len = b.length;
        ByteHandler byteHandler = new ByteHandler();
        byteHandler.write(b, off, len);
        for(String str : byteHandler.getBuffer()){
            System.out.printf(str);
        }
    }


}
